package com.zjitc.filter;

import com.alibaba.fastjson.JSON;
import com.zjitc.service.impl.UserDetailsServiceImpl;
import com.zjitc.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * JWT认证过滤器
 * 简化的版本，专注于从请求中提取JWT并验证用户身份
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 
            throws ServletException, IOException {
        try {
            // 从请求头中获取JWT令牌（尝试多个可能的请求头）
            String jwt = getJwtFromRequest(request);
            
            // 验证JWT令牌是否有效
            if (StringUtils.hasText(jwt) && JwtUtil.validateToken(jwt)) {
                // 从JWT中获取用户名
                String username = JwtUtil.getUsernameFromToken(jwt);
                
                // 从JWT中获取权限信息
                Claims claims = JwtUtil.getClaimsFromToken(jwt);
                List<String> authorities = claims.get("authorities", List.class);
                
                Collection<SimpleGrantedAuthority> authoritiesCollection = new ArrayList<>();
                if (authorities != null) {
                    authoritiesCollection = authorities.stream()
                            .map(SimpleGrantedAuthority::new)
                            .collect(Collectors.toList());
                }
                
                // 创建身份验证令牌（直接使用JWT中的权限信息）
                UsernamePasswordAuthenticationToken authentication = 
                        new UsernamePasswordAuthenticationToken(
                                username, null, authoritiesCollection);
                
                authentication.setDetails(
                        new WebAuthenticationDetailsSource().buildDetails(request));
                
                // 设置当前用户的安全上下文
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            logger.error("无法进行JWT身份验证", e);
        }
        
        // 继续过滤器链
        filterChain.doFilter(request, response);
    }
    
    /**
     * 从请求中提取JWT令牌，尝试多个可能的请求头
     */
    private String getJwtFromRequest(HttpServletRequest request) {
        // 尝试从Jwt头获取
        String jwt = request.getHeader("Jwt");
        
        // 如果Jwt头没有，尝试从Authorization头获取
        if (!StringUtils.hasText(jwt)) {
            String bearerToken = request.getHeader("Authorization");
            if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
                jwt = bearerToken.substring(7);
            }
        }
        
        return jwt;
    }
} 